package com.gitee.feizns.data.impl;

import com.gitee.feizns.data.Column;
import com.gitee.feizns.data.Table;
import lombok.SneakyThrows;

import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * @author feizns
 * @since 2019/7/6 0006
 */
public class TableImpl implements Table {

    private String name;

    private DatabaseMetaData metaData;

    public TableImpl(String name, DatabaseMetaData metaData) {
        this.name = name;
        this.metaData = metaData;
    }

    @Override
    public String getName() {
        return name;
    }

    @SneakyThrows
    @Override
    public String getComment() {
        ResultSet tables = metaData.getTables(null, null, name, null);
        if ( tables.next() )
            return tables.getString("REMARKS");
        return null;
    }

    @SneakyThrows
    @Override
    public List<Column> getColumns() {
        List<Column> ret = new ArrayList<>();
        ResultSet columns = metaData.getColumns(null, null, name, null);
        ResultSetMetaData metaData = columns.getMetaData();
        while ( columns.next() ) {
            ret.add(toColumn(columns));
        }
        return ret;
    }

    @SneakyThrows
    private Column toColumn(ResultSet rs) {
        ColumnImpl.ColumnImplBuilder builder = ColumnImpl.builder();
        builder.name(rs.getString("COLUMN_NAME"));
        builder.typeName(rs.getString("TYPE_NAME"));
        builder.comment(rs.getString("REMARKS"));
        builder.isAuto(rs.getBoolean("IS_AUTOINCREMENT"));
        builder.charLength(rs.getInt("CHAR_OCTET_LENGTH"));
        builder.isNullable(rs.getBoolean("NULLABLE"));
        return builder.build();
    }

}
